package com.gancp.controller;

import com.gancp.common.Constans;
import com.gancp.controller.BaseController.BaseController;
import com.gancp.domain.Attend;
import com.gancp.service.AttendBiz;
import com.gancp.utills.PageHelperUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by GCP on 2018/5/1.
 * 打卡业务控制层
 */
@Controller
@RequestMapping("attend")
public class AttendController extends BaseController {
    private Logger log = LoggerFactory.getLogger( "AttendController" );
    @Autowired
    private AttendBiz attendBiz;

    @RequestMapping
    public ModelAndView toAttend(HttpServletRequest request) throws Exception {
        PageInfo<Attend> pageInfo = query( request );
        log.info( getUserName( request ) + "用户查看了我的考勤界面！" );
        return new ModelAndView( "attend" ).addObject( Constans.PAGE_INFO, pageInfo );
    }

    @RequestMapping("/signAttend")
    public @ResponseBody
    String signAttend(HttpServletRequest request) throws Exception {
        Attend attend = new Attend();
        attend.setAttendDate( new Date() );
        attend.setUserid( getUserId( request ) );
        // 调用打卡业务逻辑
        String message = attendBiz.signAttend( attend );
        return message;
    }

    @RequestMapping("/attendList")
    public @ResponseBody
    PageInfo queryCord(HttpServletRequest request, Model model) throws Exception {
        PageInfo<Attend> pageInfo = query( request );
        return pageInfo;

    }

    private PageInfo<Attend> query(HttpServletRequest request) throws Exception {
        Long userId = getUserId( request );
        List<Attend> attendList = null;
        PageInfo<Attend> pageInfo = null;
        Map<String, Object> param = new HashMap<String, Object>();
        param.put( "userid", userId );
        String rangeDate = request.getParameter( "rangeDate" );
        if (!StringUtils.isEmpty( rangeDate )) {
            param.put( "beginday", rangeDate.split( "/" )[0] );
            param.put( "endDay", rangeDate.split( "/" )[1] );
        }
        try {
            PageHelperUtils.execute( request );
            attendList = attendBiz.selectAttendsPage( param );
            pageInfo = new PageInfo<Attend>( attendList );
        } catch (Exception e) {
            log.error( e.getMessage() );
            throw e;
        }
        return pageInfo;
    }
}